<template>
  <div id="container"></div>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue';
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

onMounted(() => {

  // 1.创建场景
  const scene = new THREE.Scene();

  // 2.创建相机
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 10
  camera.position.y = 10
  camera.lookAt(0, 2, 0)

  // 3.渲染场景
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight)

  // 设置场景的背景色
  renderer.setClearColor('pink')

  document.getElementById('container').appendChild(renderer.domElement)

  // 4.创建一个立方体
  // const geometry = new THREE.BoxGeometry(2, 2, 2);

  // 创建球体
  const geometry = new THREE.SphereGeometry(2);
  // 颜色贴图
  // const texture = new THREE.TextureLoader().load( "textures/300.jpg" );

  // 创建环境贴图
  const cubetexture = new THREE.CubeTextureLoader().setPath('/textures/').load([
    '1.jpg', '2.jpg',
    '3.jpg', '4.jpg',
    '5.jpg', '6.jpg'
  ])


  // 5.设置几何体材质
  const material = new THREE.MeshBasicMaterial({
    // color: 0x4781c9
    // map:texture
    envMap: cubetexture  // 镜面反射
  });

  scene.background = cubetexture

  // 6.贴合材质
  const cube = new THREE.Mesh(geometry, material);
  cube.position.set(0, 2, 0)
  scene.add(cube)

  // 添加网格线
  const gridHelper = new THREE.GridHelper(10, 10);
  scene.add(gridHelper);


  // 创建轨道控制器
  const controls = new OrbitControls(camera, renderer.domElement);

  // 设置轨道控制自转
  controls.autoRotate = true
  controls.autoRotateSpeed = 1

  // 设置轨道阻尼
  controls.enableDamping = true
  controls.dampingFactor = 0.01


  // 添加坐标轴
  const axesHelper = new THREE.AxesHelper(5);
  scene.add(axesHelper);


  function animate() {
    requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    // 调用update方法才能生效
    controls.update()
    renderer.render(scene, camera);
  }
  animate();


})

</script>

<style lang="scss" scoped></style>